import { Component, OnInit, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';

import { orderStateArrs } from '../../used-store/used-store-manage.pipe';
import { CommonService } from '../../../../app/services-common/common.service';
import { FinanceSecondOrderService } from './finance-second-order.service';

@Component({
  selector: 'app-finance-second-order',
  templateUrl: './finance-second-order.component.html',
  styleUrls: ['./finance-second-order.component.scss']
})
export class FinanceSecondOrderComponent implements OnInit {

  @ViewChild('followUpRef') followUpRef: any;

  statusOptions = [...orderStateArrs]; // 订单状态

  searchOptions = [
    { type: 1, labelText: '订单编号', valueKey: 'orderNum', value: '' },
    {
      type: 2,
      labelText: '订单状态',
      valueKey: 'statusList',
      value: [],
      multiple: true,
      notTostr: true,
      selectOptions: this.statusOptions,
    },
    {
      type: 2,
      labelText: '货主',
      valueKey: 'supplierIdList',
      value: [],
      multiple: true,
      notTostr: true,
      selectBindKey: {
        key: 'id',
        label: 'name'
      },
      selectOptions: [],
    },
    { type: 1, labelText: '交易流水', valueKey: 'payOrderNum', value: '' },
    { type: 1, labelText: '机器编码', valueKey: 'equipmentCode', value: '', placeholder: '请输入机器编码号/imei/序列号' },
    { type: 3, labelText: '下单时间', valueKey: ['createTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '付款时间', valueKey: ['beginPayTime', 'endPayTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '发货时间', valueKey: ['beginShipTime', 'endShipTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '收货时间', valueKey: ['receiptTime', 'receiptEndTime'], value: [], isTimeSelect: true },
  ];
  searchParams: any = {};

  // 货主
  supplierOptions: any = [];
  
  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };
  exportLoading: boolean = false;

  // 跟进 Modal
  initParams: any = {
    type: 1, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  constructor(
    private message: NzMessageService,
    private commonService: CommonService,
    private modal: NzModalService,
    private services: FinanceSecondOrderService
  ) { }

  ngOnInit(): void {
    this.querySupplierOptions();
  }

  // 查询货主
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.commonService.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name);
      
      let temIndex = this.searchOptions.findIndex((item: any) => item.valueKey === 'supplierIdList');
      this.searchOptions[temIndex].selectOptions = this.supplierOptions;
    } else {
      this.message.error(res.message);
    }
  }

  async loadTable() {
    let datas = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    const { code, data, message }: any = await this.services.querySecondOrderList(datas);
    if (code === 0) {
      const { records, total } = data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }

  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  // 跟进
  followModal(item: any) {
    this.initParams.relationInformation = item.orderNum;
    this.followUpRef.isModelVisible = true;
  }

  exportTable() {
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的数据，为了导出速度请尽可能的控制时间范围。确认导出？',
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          ...this.searchParams
        }
        for (let key in params) {
          if (params[key] === null) {
            params[key] = '';
          }
    
          if (Array.isArray(params[key])) {
            params[key] = params[key].length ? params[key].join(',') : '';
          }
        }

        this.exportLoading = true;
        const res: any = await this.services.exportSecondOrderData(params);
        this.exportLoading = false;
        
        if (res.type == 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '财务二手商城订单管理');
        } else {
          this.message.error('导出失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  orderNameFilter(status: any, type: string) {
    let tempObj = this.statusOptions.find((item: any) => {
      return item.value == status;
    })

    if (type == 'text') {
      return tempObj?.label || '-';
    } else if (type == 'color') {
      return tempObj?.color || '';
    } else {
      return '';
    }
  }
}
